<template>
  <div class="detail">
    <NavBar></NavBar>
    <ArticleHead ref="head"></ArticleHead>
    <ArticleMain
      :content="this.content"
      ref="main"
      @click-comment="scrollToCmtList"
    ></ArticleMain>
    <ArticleComments @click-comment="scrollToCmtList"></ArticleComments>
    <div class="back-top" @click="scrollToTop">
      <van-icon name="back-top" />
    </div>
  </div>
</template>

<script>
import NavBar from "@/components/Home/NavBar";
import ArticleHead from "@/components/Community/ArticleHead";
import ArticleMain from "@/components/Community/ArticleMain";
import ArticleComments from "@/components/Community/ArticleComments";
import { getArticleContentAPI } from "@/api/articleApi";
import { animate } from "popmotion";
import { mapActions, mapState } from "vuex";
export default {
  components: {
    NavBar,
    ArticleHead,
    ArticleMain,
    ArticleComments,
  },
  props: ["id"],
  data() {
    return {
      content: "",
    };
  },
  computed: {
    ...mapState("article", ["article"]),
  },
  methods: {
    ...mapActions("article", ["initArticle"]),
    async initArticleAndContent() {
      this.initArticle(this.id);
      const { data: response } = await getArticleContentAPI(this.id);
      if (response.message == "OK") {
        this.content = response.data;
      }
    },
    // 滚动到评论的列表区域
    scrollToCmtList() {
      // 1. 当前滚动条的位置
      const now = window.scrollY + 46 + this.$refs.head.$el.offsetHeight;
      // 2. 目标位置（文章信息区域的高度）
      const dist = this.$refs.main.$el.offsetHeight;
      console.log(dist);

      // 3. 实现滚动动画
      animate({
        from: now, // 当前的位置
        to: dist, // 目标位置
        onUpdate: (latest) => window.scrollTo(0, latest),
      });
    },
    scrollToTop() {
      const now = window.scrollY;
      const dist = 0;
      animate({
        from: now, // 当前的位置
        to: dist, // 目标位置
        onUpdate: (latest) => window.scrollTo(0, latest),
      });
    },
  },
  created() {
    this.initArticleAndContent();
  },
};
</script>

<style lang="less">
.detail {
  padding-bottom: 50px;
}

.back-top {
  display: flex;
  width: 40px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  position: fixed;
  right: 10px;
  bottom: 80px;
  background-color: lightgreen;
  opacity: 0.8;
  border-radius: 20px;
  align-items: center;
  justify-content: center;
}
</style>
